package com.jmxcfc.blfsc.huisheng.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jmxcfc.blfsc.common.exception.NotifyException;
import com.jmxcfc.blfsc.huisheng.common.Constants;
import com.jmxcfc.blfsc.huisheng.entity.SendDetailSub;
import com.jmxcfc.blfsc.huisheng.entity.VoiceNotifyRecord;
import com.jmxcfc.blfsc.huisheng.entity.vo.NotifyResponseVo;
import com.jmxcfc.blfsc.huisheng.mapper.VoiceNotifyRecordMapper;
import com.jmxcfc.blfsc.huisheng.service.ISendDetailSubService;
import com.jmxcfc.blfsc.huisheng.service.IVoiceNotifyRecordService;
import com.jmxcfc.blfsc.huisheng.thread.SyncSendNotifyResultOperator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 * 94语音回调记录表 服务实现类
 * </p>
 *
 * @author pbs
 * @since 2024-06-24
 */
@Service
@Slf4j
public class VoiceNotifyRecordServiceImpl extends ServiceImpl<VoiceNotifyRecordMapper, VoiceNotifyRecord> implements IVoiceNotifyRecordService {

    private ISendDetailSubService sendDetailSubService;

    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    public void setSendDetailSubService(ISendDetailSubService sendDetailSubService) {
        this.sendDetailSubService = sendDetailSubService;
    }

    @Autowired
    public void setThreadPoolTaskExecutor(ThreadPoolTaskExecutor threadPoolTaskExecutor) {
        this.threadPoolTaskExecutor = threadPoolTaskExecutor;
    }

    /**
     * 数据结果推送
     *处理流程:
     *(2)根据caseId查询HUISHENG_SEND_DETAIL_SUB是否存在发送记录
     *(3)通知记录落库
     *(4)同步响应慧声语音接收通知结果,
     回调返回成功的标准是http状态码为200，并且返回的内容体的status参数也为200:
     {
        "code":"20000",
        "msg":"处理正常",
        "data":null
     }
     *
     * 异步调用blfs-sms模块的发送状态通知接口:
     1)通知状态的判断:
     根据慧声语音的通知参数 result（结果：成功、失败）
     2)请求参数组织
     * @param encryptNotifyContent 通知内容
     * @return
     */
    @Override
    public NotifyResponseVo voiceNotifyHandler(String encryptNotifyContent) {
        try {
            if (StringUtils.isAnyBlank(encryptNotifyContent)){
                log.error("慧声语音-【数据推送回调】,回调通知请求参数存在空值或者错误,结束处理,数据接收失败,通知数据data:{}", encryptNotifyContent);
                return NotifyResponseVo.fail("通知参数存在为空或者错误");
            }else{
                JSONObject content = Optional.ofNullable(JSON.parseObject(encryptNotifyContent))
                        .orElseThrow(() -> {
                            log.error("慧声语音-【数据推送回调】,通知数据:{},json解析异常", encryptNotifyContent);
                            return new NotifyException();
                        });
                JSONObject data = Optional.ofNullable(content.getJSONObject(Constants.NOTIFY_DATE))
                        .orElseThrow(() -> {
                            log.error("慧声语音-【数据推送回调】,通知数据content:{},json解析异常", content);
                            return new NotifyException();
                        });
                List<JSONObject> itemList = Optional.ofNullable(JSON.parseArray(data.getString(Constants.NOTIFY_ITEMS),JSONObject.class))
                        .orElseThrow(() -> {
                            log.error("慧声语音-【数据推送回调】,通知数据data:{},json解析异常", data);
                            return new NotifyException();
                        });
                log.info("慧声语音-【数据推送回调】,通知数据item:{}",itemList);
                for (JSONObject item : itemList){
                    String caseId = Optional.ofNullable(item.getString(Constants.NOTIFY_CASE_ID)).orElse("");
                    SendDetailSub sendDetailSub = sendDetailSubService.getById(caseId);
                    if (Objects.isNull(sendDetailSub)) {
                        log.error("慧声语音-【数据推送回调】,根据通知参数caseId【标识一条语音的流水号uuid】:{} 慧声语音厂商发送明细表未查询到发送记录数据",caseId);
                        continue;
                    }
                    VoiceNotifyRecord voiceNotifyRecord = new VoiceNotifyRecord();
                    voiceNotifyRecord.setCaseId(caseId);
                    voiceNotifyRecord.setRequestNo(sendDetailSub.getRequestNo());
                    voiceNotifyRecord.setRequestId(sendDetailSub.getRequestId());
                    //回传结果对应赋值
                    BeanUtil.copyProperties(item, voiceNotifyRecord);
                    //存在短信发送结果对短信相关回调字符赋值
                    if(!Objects.isNull(item.getString(Constants.NOTIFY_SMS_INFO))){
                        JSONObject smsInfo = item.getJSONObject(Constants.NOTIFY_SMS_INFO);
                        voiceNotifyRecord.setSmsPhoneNumber(Optional.ofNullable(smsInfo.getString(Constants.NOTIFY_SMS_PHONE_NUMBER)).orElse(""));
                        voiceNotifyRecord.setSmsSendTime(Optional.ofNullable(smsInfo.getString(Constants.NOTIFY_SMS_SEND_TIME)).orElse(""));
                        voiceNotifyRecord.setSmsContent(Optional.ofNullable(smsInfo.getString(Constants.NOTIFY_SMS_CONTENT)).orElse(""));
                        voiceNotifyRecord.setSmsStatus(Optional.ofNullable(smsInfo.getString(Constants.NOTIFY_SMS_STATUS)).orElse(""));
                    }

                    this.save(voiceNotifyRecord);
                    log.info("慧声语音-【数据推送回调】,caseId【标识一条语音的流水号uuid】:{},通知数据落库成功",caseId);
                    //异步发起调用blfs-sms 进行发送状态(语音发送状态) 通知
                    threadPoolTaskExecutor.execute(new SyncSendNotifyResultOperator(caseId,sendDetailSub, voiceNotifyRecord));
                }
            }
        } catch (Exception e) {
            log.error("慧声语音-【数据推送回调】,异常信息:{}", e.getMessage(), e);
            throw new NotifyException();
        }
        return NotifyResponseVo.success();
    }
}
